const mongoose = require('mongoose')
const glob = require('glob')
const path = require('path')
const dbAddress = 'mongodb://118.25.208.36:1024/mpvue_pro'
// 数据库连接次数
let connectCount = 0

exports.connectDb = () => {
  mongoose.set('useCreateIndex', true)
  mongoose.connect(dbAddress, {
    useNewUrlParser: true
  })
  mongoose.connection.on('disconnected', () => {
    if (connectCount < 3) {
      mongoose.connect(dbAddress)
      connectCount++
    } else {
      throw new Error('数据库出现问题-disconnected')
    }
  })
  mongoose.connection.on('error', (err) => {
    if (connectCount < 3) {
      mongoose.connect(dbAddress)
      connectCount++
    } else {
      throw new Error('数据库出现问题-error', err)
    }
  })
  mongoose.connection.once('open', () => {
    console.log('数据库连接成功')
  })
}
exports.initSchema = () => {
  glob.sync(path.resolve(__dirname, './schema/', '**/*.js')).forEach(require)
}
